import React, { Component } from "react";
import { View, Text, TextInput, TouchableOpacity,DeviceEventEmitter } from "react-native";
import NavBarConfig from "../modules/NavBar";
import {
  BGT_INFO,
  REDEEM_CODE,
  REDEEM,
  MEMBER,
  MEMBER_BGT
} from "../../config/Api";
import http from "../../util/http";
import Base64 from "../../util/base64";
import { toast } from "../../util/tip";
import { getTimer, checkNumber } from "../../util/util";
import redeemStyles from "../../style/pages/redeem";
import scriptionStyles from "../../style/pages/subscription";
import { Color } from "../../style/common";
import { UNSET_PASSWORD } from "../../util/Const";

class Redeem extends Component {
  static navigationOptions = ({ navigation }) =>
    NavBarConfig(
      {
        headerTitle: "贖回",
        headerRight: []
      },
      navigation
    );

  state = {
    rate: 0,
    tel: "",
    verifyMsg: "獲取驗證碼",
    bgt: {},

    code: "",
    password: "",
    address: "",
    amount: "",
    amountShow: 0,

    isCodeRequesting: false,
    isSubmitRequeting: false
  };
  handleSetAll() {
    this.state.amount.value = this.state.amountShow;
  }

  async initBgtInfo() {
    const data = await http.get(MEMBER_BGT);
    this.setState({
      amountShow: data.data.amount - data.data.freeze_amount
    });
  }

  async getMemberInfo() {
    const data = await http.get(MEMBER);
    this.setState({
      tel: data.data.tel
    });
  }

  async getWalletInfo() {
    const data = await http.get(BGT_INFO);
    this.setState({
      rate: data.data.fee_rate,
      bgt: data.data
    });
  }

  componentWillMount() {
    this.getMemberInfo();
    this.getWalletInfo();
    this.initBgtInfo();
    
    this.subscription = DeviceEventEmitter.addListener(UNSET_PASSWORD, () => {
      this.props.navigation.navigate("SetTradePassword");
    });
  }

  componentWillUnmount() {
    this.subscription.remove();
  }

  async handleSendCode() {
    if (this.state.isCodeRequesting) return;
    const value = this.state.tel;
    if (!value) {
      return;
    }

    this.setState({
      isCodeRequesting: true
    });
    const data = await http.post(REDEEM_CODE, {
      tel: value
    });
    if (data) {
      getTimer(
        50,
        time => {
          this.setState({
            verifyMsg: `${time}s`
          });
        },
        () => {
          this.setState({
            verifyMsg: "獲取驗證碼"
          });
        }
      );
    }
    this.setState({
      isCodeRequesting: false
    });
  }

  handleChange(key, text) {
    const data = {};
    data[key] = text;
    this.setState({
      ...data
    });
  }

  async handleSubmitGetMoney() {
    if (this.state.isSubmitRequeting) return;
    const amount = this.state.amount.trim();
    const password = this.state.password.trim();
    const code = this.state.code.trim();
    const address = this.state.address.trim();
    if (!checkNumber(amount)) {
      toast("份额需为数字");
      return;
    }
    if (!amount) {
      toast("請填寫正確的金額");
      return;
    }
    if (!password) {
      toast("請填寫支付密碼");
      return;
    }
    if (!code) {
      toast("請填寫正確的驗證碼");
      return;
    }
    if (!address) {
      toast("請填寫正確的驗證碼");
      return;
    }
    this.setState({
      isSubmitRequeting: true
    });
    const data = await http.post(REDEEM, {
      amount: amount,
      password: Base64.encode(password),
      code: code,
      address: address
    });
    if (data) {
      toast("提交贖回申請成功");
      this.props.navigation.goBack();
    }
    this.setState({
      isSubmitRequeting: false
    });
  }
  render() {
    return (
      <View>
        <View style={[scriptionStyles.subItem, { backgroundColor: "white" }]}>
          <Text
            style={[
              scriptionStyles.subListItem,
              {
                flex: 1
              }
            ]}
          >
            当前赎回比
          </Text>
          <Text style={[scriptionStyles.subListItem]}>
            {parseFloat(this.state.bgt.usdt_rate || 10)} BGT : 1 USDT 
          </Text>
        </View>
        <View style={redeemStyles.container}>
          <Text style={redeemStyles.h4}>贖回份額：</Text>
          <View style={redeemStyles.reddemItem}>
            <TextInput
            underlineColorAndroid="transparent"
              placeholder={
                "請輸入贖回份額(最多可贖回" + this.state.amountShow + ")"
              }
              style={redeemStyles.input}
              keyboardType="numeric"
              onChangeText={text => this.handleChange("amount", text)}
            />
            <TouchableOpacity onClick={this.handleSetAll.bind(this)}>
              {/* <Text style={redeemStyles.a}>全部</Text> */}
            </TouchableOpacity>
          </View>
          <View style={redeemStyles.reddemItem}>
            <TextInput
            underlineColorAndroid="transparent"
              style={redeemStyles.input}
              placeholder="請輸入usdt地址"
              onChangeText={text => this.handleChange("address", text)}
            />
          </View>
          <View style={redeemStyles.reddemItem}>
            <TextInput
            underlineColorAndroid="transparent"
              placeholder="請輸入獲取驗證碼"
              style={redeemStyles.input}
              onChangeText={text => this.handleChange("code", text)}
            />
            <TouchableOpacity
              onPress={this.handleSendCode.bind(this)}
              disabled={
                this.state.isCodeRequesting ||
                !this.state.tel ||
                this.state.verifyMsg !== "獲取驗證碼"
              }
            >
              <Text
                style={[
                  redeemStyles.button,
                  {
                    backgroundColor:
                      this.state.isCodeRequesting ||
                      !this.state.tel ||
                      this.state.verifyMsg !== "獲取驗證碼"
                        ? "gray"
                        : Color
                  }
                ]}
              >
                {this.state.verifyMsg}
              </Text>
            </TouchableOpacity>
          </View>
          <View style={redeemStyles.reddemItem}>
            <TextInput
            underlineColorAndroid="transparent"
              password={true}
              secureTextEntry={true}
              style={redeemStyles.input}
              placeholder="請輸入支付密碼"
              onChangeText={text => this.handleChange("password", text)}
              maxLength={6}
            />
          </View>

          <Text style={redeemStyles.redeemTip}>
            手續費(
            {this.state.rate}
            %)
          </Text>
          <Text style={redeemStyles.reddemTip}>
            usdt地址若填写错误资产将不可找回，概不负责。
          </Text>
          <TouchableOpacity onPress={this.handleSubmitGetMoney.bind(this)}>
            <Text style={redeemStyles.redeemConfirm}>確定</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}

export default Redeem;
